<template>
  <div class="main-container">
    <el-form inline>
      <el-form-item>
        <h1>公司生产汇总报表</h1>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="monthRange" type="monthrange" value-format="yyyy-MM" align="right" unlink-panels range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table border stripe :data="summaryList" :summary-method="calcSummaries" show-summary>
      <el-table-column prop="month" label="月份" align="center" header-align="center" width="200"></el-table-column>
      <el-table-column prop="quotaWorkHour" label="定额工时" align="right" header-align="center" min-width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.quotaWorkHour.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="realWorkHour" label="实动工时" align="right" header-align="center" min-width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.realWorkHour.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="quotaRate" label="定额完成率" align="center" header-align="center" min-width="100">
        <template slot-scope="scope">
          <span>{{ (scope.row.quotaRate * 100).toFixed(0) }} %</span>
        </template>
      </el-table-column>
      <el-table-column prop="equipmentRate" label="设备开动率" align="center" min-width="100">
        <template slot-scope="scope">
          <span>{{ (scope.row.equipmentRate * 100).toFixed(0) }} %</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showWorkerDetail(scope.row)">人员明细</el-button>
          <el-button type="primary" size="mini" @click="showEquipmentDetail(scope.row)">设备明细</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <div ref="echarts1" style="width: 100%; height: 400px"></div>
      <div ref="echarts2" style="width: 100%; height: 400px"></div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { getProductionSummaryReportApi } from '@/api/report/api_report_work_hour'
import * as echarts from 'echarts'

@Component({
  components: {}
})
export default class ProductionSummary extends Vue {
  private chart1!: echarts.ECharts
  private chart2!: echarts.ECharts
  monthRange: any = []
  summaryList: any = []

  /**
   * 生命周期函数：组件加载
   * 1. 数据初始化查询，默认本年初至本月
   */
  created() {
    this.initMonthRangeParam()
    this.query()
  }

  initChart() {
    const chartDom1 = this.$refs.echarts1 as HTMLDivElement
    const chartDom2 = this.$refs.echarts2 as HTMLDivElement
    this.chart1 = echarts.init(chartDom1)
    this.chart2 = echarts.init(chartDom2)

    const x = this.summaryList.map(item => item.month)
    const y1 = this.summaryList.map(item => item.quotaWorkHour)
    const y2 = this.summaryList.map(item => item.realWorkHour)
    const y3 = this.summaryList.map(item => item.quotaRate)
    const y4 = this.summaryList.map(item => item.equipmentRate)

    const option1 = {
      title: {
        text: '定额完成率'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['定额工时', '实动工时', '定额完成率']
      },
      xAxis: {
        type: 'category',
        data: x
      },
      yAxis: [
        {
          type: 'value',
          name: '工时',
          axisLabel: {
            formatter: '{value} H'
          }
        },
        {
          type: 'value',
          name: '定额完成率',
          min: 0,
          max: 1,
          axisLabel: {
            formatter: '{value}'
          }
        }
      ],
      series: [
        {
          name: '定额工时',
          type: 'bar',
          data: y1
        },
        {
          name: '实动工时',
          type: 'bar',
          data: y2
        },
        {
          name: '定额完成率',
          type: 'line',
          yAxisIndex: 1,
          data: y3
        }
      ]
    }

    const option2 = {
      title: {
        text: '设备开动率'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: x
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '设备开动率',
          type: 'line',
          data: y4
        }
      ]
    }

    this.chart1.setOption(option1)
    this.chart2.setOption(option2)
  }

  /**
   * 初始化本年份数据
   * 年初至本月
   */
  private initMonthRangeParam() {
    const today = new Date()
    let month = today.getMonth() + 1
    let monthStr = month < 10 ? '0' + month : month
    const end = today.getFullYear() + '-' + monthStr
    const start = today.getFullYear() + '-01'
    this.monthRange = [start, end]
  }

  /**
   * 异步查询方法
   * 获取报表数据
   */
  async query() {
    console.log('查询时间：' + this.monthRange)
    await getProductionSummaryReportApi({
      beginMonth: this.monthRange[0] + '-01',
      endMonth: this.monthRange[1] + '-01'
    })
      .then(res => (this.summaryList = res.data))
      .then(() => this.initChart())
  }

  /**
   * 计算表尾行
   * 合计 定额工时与实动工时
   * 平均 定额完成率与设备开动率
   */
  calcSummaries(params) {
    const { columns, data } = params
    const sums: any = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      const values = data.map(item => Number(item[column.property]))
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        if (index === 1 || index === 2) {
          sums[index] = sums[index].toFixed(2)
        }
        if (index === 3 || index === 4) {
          sums[index] = ((sums[index] / data.length) * 100).toFixed(0) + '%'
        }
      } else {
        sums[index] = ' '
      }
    })

    return sums
  }

  /**
   * 跳转至工人工时报表页面，
   * 初始查询时间范围为上月24日至本月23日
   */
  showWorkerDetail(row) {
    this.$router.push({
      name: 'ReportWorkHourOperator',
      params: {
        from: 'production_summary',
        month: row.month
      }
    })
  }

  /**
   * 跳转至设备工时报表页面，
   * 初始查询时间范围为上月24日至本月23日
   */
  showEquipmentDetail(row) {
    this.$router.push({
      name: 'ReportWorkHourEquipment',
      params: {
        from: 'production_summary',
        month: row.month
      }
    })
  }
}
</script>

<style></style>
